﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using System.ComponentModel;

namespace Behaviors
{
    /// <summary>
    /// Fires when a text box goes from is empty to something else.
    /// </summary>
    public class TextBoxValueStatusChanged : TriggerBase<TextBox>
    {
        /// <summary>
        /// If set to true, trigger will fire when the text box is empty. If false, when it becomes non-empty.
        /// </summary>
        [Description("If true, fire when tb becomes empty. False does the opposite")]
        public bool FireIfEmpty
        {
            get { return (bool)GetValue(FireIfEmptyProperty); }
            set { SetValue(FireIfEmptyProperty, value); }
        }

        // Using a DependencyProperty as the backing store for FireIfEmpty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty FireIfEmptyProperty =
            DependencyProperty.Register("FireIfEmpty", typeof(bool), typeof(TextBoxValueStatusChanged), new PropertyMetadata(true));

        /// <summary>
        /// Track the state, incase we miss something.
        /// </summary>
        bool isEmptyNow;

        /// <summary>
        /// Attach and init for our text box.
        /// </summary>
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.TextChanged += new TextChangedEventHandler(AssociatedObject_TextChanged);
            isEmptyNow = AssociatedObject.Text.Length == 0;
        }

        /// <summary>
        /// Disconnect ourselves
        /// </summary>
        protected override void OnDetaching()
        {
            AssociatedObject.TextChanged -= new TextChangedEventHandler(AssociatedObject_TextChanged);
            base.OnDetaching();
        }

        /// <summary>
        /// See if the value of the thing has changed from empty to not empty.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void AssociatedObject_TextChanged(object sender, TextChangedEventArgs e)
        {
            bool nowEmpty = AssociatedObject.Text.Length == 0;

            if (nowEmpty != isEmptyNow)
            {
                if (nowEmpty && FireIfEmpty)
                {
                    InvokeActions(null);
                }
                else if (!nowEmpty && !FireIfEmpty)
                {
                    InvokeActions(null);
                }

                isEmptyNow = nowEmpty;
            }
        }
    }
}
